import $store from "@/store/index";
import Vue from "vue"
let prototype = Vue.prototype;

function findApi(name) {
    let pos = name.indexOf('.');
    if (pos > 0) {
        let temp, arr = name.split('.');
        for (let i = 0; i < arr.length; i++) {
            if (i == 0) {
                temp = prototype.$apis[arr[i]] || {};
            } else {
                temp = temp[arr[i]] || {};
            }
        }
        return temp;
    }

    return name;
}

const request = async (args) => {
    const rule = findApi(args.api || '');
    if (JSON.stringify(rule) === "{}") {
        throw "找不到API：" + args.api;
    }

    const query = (args.query) ? '?' + args.query : '';

    if (typeof rule.auth !== "undefined" && rule.auth === true && !$store.state.user.token) {
        $store.commit("user/showLoginModal", true);
        throw "登录态失效";
    }

    (rule.showLoading) && prototype.$loading.show('加载中');

    const contentType = (args.contentType) ? args.contentType : 'application/json';

    const [error, response] = await uni.request({
        url: prototype.$config.root + rule.url + query,
        method: rule.method || 'post',
        data: args.data,
        header: {
            "XX-Wxapp-AppId": prototype.$config.appId,
            'XX-Token': $store.state.user.token,
            'XX-Device-Type': 'wxapp',
            'X-Requested-With': 'XMLHttpRequest',
            'content-type': contentType,
        }
    });

    (rule.showLoading) && prototype.$loading.hide();

    if (error || response.statusCode != 200) {
        prototype.$utils.toast('网络错误');
        throw "网络错误";
    }

    if (response.data.code == 10001) {
        prototype.$models.user.logout();
        $store.commit("user/showLoginModal", true);
        throw "登录态失效";
    }

    return Promise.resolve(response.data);
};

export default request